//
//  NSConditionDemo.m
//  MultiperThreadTest02
//
//  Created by FelixYin on 2020/4/5.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "NSConditionDemo.h"

@interface NSConditionDemo ()

@property (nonatomic,strong) NSCondition *ticketLock;
@property (nonatomic,strong) NSCondition *moneyLock;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSCondition *dataLock;

@end

@implementation NSConditionDemo

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.ticketLock = [[NSCondition alloc] init];
        self.moneyLock = [[NSCondition alloc] init];
        self.dataLock = [[NSCondition alloc] init];
        self.dataArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)saveMoney{
    [self.moneyLock lock];
    [super saveMoney];
    [self.moneyLock unlock];
}

- (void)drawMoney{
    [self.moneyLock lock];
    [super drawMoney];
    [self.moneyLock unlock];
}

- (void)saleTicket{
    [self.ticketLock lock];
    [super saleTicket];
    [self.ticketLock unlock];
}

- (void)test {
    [[[NSThread alloc] initWithTarget:self selector:@selector(remove) object:nil] start];
    sleep(4);
    [[[NSThread alloc] initWithTarget:self selector:@selector(add) object:nil] start];
}

//添加数据
- (void) add{
    [self.dataLock lock];
    NSLog(@"添加元素");
    [self.dataArray addObject:@"数据"];
    //通知一个线程
    [self.dataLock signal];

    //通知多个线程 以广播的形式
    //[self.dataLock broadcast];
    [self.dataLock unlock];
    
    NSLog(@"发送条件信号");
}

//移除最后一个数据
- (void) remove{
    [self.dataLock lock];
    if (self.dataArray.count == 0) {
        //当不满足条件时
        NSLog(@"等待条件");
        [self.dataLock wait];
    }
    NSLog(@"删除元素");
    [self.dataArray removeLastObject];
    [self.dataLock unlock];
}

@end
